# main.py - 增加错误处理
import os
import sys
from data_loader import DataLoader
from exploratory_analysis import ExploratoryAnalysis
from feature_engineering import FeatureEngineer
from customer_segmentation import CustomerSegmentation
from prediction_model import CouponPredictionModel
from strategy_design import CouponStrategy
from config import FILE_PATHS
import numpy as np
#版本2

def main():
    """主执行函数"""
    print("=" * 60)
    print("电商平台用户行为分析与挖掘系统")
    print("=" * 60)

    try:
        # 步骤1: 数据加载和预处理
        print("\n📊 步骤1: 数据加载和预处理")
        data_loader = DataLoader(FILE_PATHS['data_file'])

        if not data_loader.load_data():
            print("数据加载失败，程序退出")
            return

        if not data_loader.preprocess_data():
            print("数据预处理失败，程序退出")
            return

        data_loader.get_data_info()
        df = data_loader.get_clean_data()

        # 检查数据是否为空
        if df is None or len(df) == 0:
            print("数据为空，程序退出")
            return

        # 步骤2: 探索性数据分析
        print("\n📈 步骤2: 探索性数据分析")
        explorer = ExploratoryAnalysis(df)
        explorer.perform_complete_analysis()

        # 步骤3: 特征工程
        print("\n🔧 步骤3: 特征工程")
        feature_engineer = FeatureEngineer(df)
        user_features = feature_engineer.create_user_features()

        if user_features is None:
            print("用户特征创建失败，跳过后续步骤")
            return

        merchant_features = feature_engineer.create_merchant_features()
        feature_engineer.get_feature_summary()

        # 检查用户特征是否有效
        if user_features is None or len(user_features) == 0:
            print("用户特征为空，跳过后续步骤")
            return

        # 步骤4: 客户分群和用户画像
        print("\n👥 步骤4: 客户分群和用户画像")
        segmenter = CustomerSegmentation(user_features)

        # 寻找最佳聚类数
        features_for_clustering = segmenter.prepare_features()
        if features_for_clustering is not None and len(features_for_clustering) > 0:
            optimal_clusters = segmenter.find_optimal_clusters(features_for_clustering)

            # 执行聚类
            cluster_labels = segmenter.perform_clustering(n_clusters=min(optimal_clusters, len(user_features)))
            if cluster_labels is not None:
                segmenter.visualize_clusters()
                cluster_descriptions = segmenter.create_customer_profiles()
                segmented_users = segmenter.get_segmented_users()
            else:
                print("聚类失败，跳过后续步骤")
                return
        else:
            print("没有足够的特征进行聚类，跳过客户分群")
            segmented_users = user_features
            cluster_descriptions = {}

        # 步骤5: 预测模型构建
        print("\n🤖 步骤5: 预测模型构建")
        predictor = CouponPredictionModel(df, segmented_users)
        X, y = predictor.prepare_training_data()

        if X is not None and y is not None and len(X) > 0 and len(y) > 0:
            X_train, X_test, y_train, y_test = predictor.train_model(X, y)
            evaluation_results = predictor.evaluate_model()

            # 特征重要性分析
            feature_importance = predictor.get_feature_importance(top_n=10)
            if feature_importance is not None:
                print("\n🔍 特征重要性TOP10:")
                for _, row in feature_importance.iterrows():
                    print(f"  {row['feature']}: {row['importance']:.4f}")
        else:
            print("训练数据不足，跳过模型构建")
            predictor = None

        # 步骤6: 策略设计
        print("\n🎯 步骤6: 策略设计")
        strategy_designer = CouponStrategy(
            segmented_users,
            cluster_descriptions,
            predictor.model if predictor else None
        )

        strategy_summary = strategy_designer.create_strategy_dashboard()

        # 最终总结
        print("\n" + "=" * 60)
        print("分析完成总结")
        print("=" * 60)
        print(f"✅ 数据处理: 成功处理 {len(df)} 条订单数据")
        print(f"✅ 用户分析: 共分析 {len(user_features)} 个用户特征")
        print(f"✅ 客户分群: 识别出 {len(cluster_descriptions)} 个客户价值分群")

        if predictor and evaluation_results:
            print(f"✅ 模型构建: AUC得分 {evaluation_results['auc_score']:.4f}")
        else:
            print("⚠️  模型构建: 跳过")

        print(f"✅ 策略设计: 完成策略模块设计")

        print("\n🎉 所有分析任务已完成！")
        print("请查看上述分析结果和可视化图表，基于分析结果制定具体的优惠券投放计划。")

    except Exception as e:
        print(f"\n❌ 程序执行过程中出现错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    # 创建输出目录
    os.makedirs(FILE_PATHS['output_dir'], exist_ok=True)

    # 执行主程序
    main()